<template>
  <div class="table-box">
    <ProTable ref="proTable" title="供应商列表" :columns="columns" :data="supplierList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button type="primary" :icon="CirclePlus" @click="openDrawerStatic('新增')">新增供应商</el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <template #operation="scope">
        <el-button type="primary" link :icon="View" @click="openDrawerStatic('查看', scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="openDrawerStatic('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
      </template>
    </ProTable>
    <supplierDrawer ref="drawerRef" @refresh="initFormData" />
    <ImportExcel ref="dialogRef" />
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, onMounted } from "vue";
import { Supplier } from "@/api/interface";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import SupplierDrawer from "@/views/proTable/components/SupplierDrawer.vue";
import axios from "axios";
const supplierList = ref();
const baseUrl = import.meta.env.VITE_BASE_URL;
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Supplier.ResSupplier>[] = [
  { type: "selection", fixed: "left", width: 80 },
  {
    prop: "supplierLicense",
    label: "营业执照号码",
    search: { el: "input" }
  },
  {
    prop: "supplierName",
    label: "供应商名称",
    search: { el: "input" },
    width: 200
  },
  {
    prop: "contactName",
    label: "联系人姓名",
    search: { el: "input" }
  },
  {
    prop: "contactEmail",
    label: "联系人邮箱",
    search: { el: "input" }
  },
  {
    prop: "contactPhone",
    label: "联系人电话",
    search: { el: "input" }
  },
  {
    prop: "createTime",
    label: "创建时间",
    width: 180,
    search: {
      el: "date-picker",
      span: 2,
      props: { type: "datetimerange", valueFormat: "YYYY-MM-DD HH:mm:ss" },
      defaultValue: ["2022-11-12 11:35:00", "2022-12-12 11:35:00"]
    }
  },
  { prop: "operation", label: "操作", fixed: "right", width: 280 }
];

//删除
const deleteAccount = async (params: Supplier.ResSupplier) => {
  ElMessageBox.confirm("是否删除该项?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning", // 使用字符串形式的类型
    draggable: true
  })
    .then(async () => {
      try {
        const response = await axios.post(baseUrl + "/api/carbon/deleteSupplier", {
          id: params.id
        });
        if (response.data && response.data.code === 200) {
          ElMessage({
            type: "success",
            message: "删除供应商成功!"
          });
          await initFormData(); // 删除成功后刷新列表
        } else {
          ElMessage.error(response.data.msg || "删除失败");
        }
      } catch (error) {
        console.error("删除供应商出错:", error);
        ElMessage.error("删除供应商失败，可能是因为参数错误或网络问题");
      }
    })
    .catch(() => {
      // 如果用户取消了操作，则不做任何处理
    });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof SupplierDrawer> | null>(null);

// 静态方法（操作静态数组）
const openDrawerStatic = (title: string, row: Partial<Supplier.ResSupplier> = {}) => {
  // 定义静态操作
  const params = {
    title,
    isView: title === "查看",
    row: { ...row } // 静态模式下仅操作此行数据
  };
  drawerRef.value?.acceptParams(params);
};

onMounted(async () => {
  await initFormData();
});

/**初始化数据 */
const initFormData = async () => {
  try {
    //数据库
    const response = await axios.get(baseUrl + "/api/carbon/getAllSuppliers");
    console.log("响应数据_读取供应商列表:", response.data);
    if (response.data && response.data.code === 200) {
      supplierList.value = response.data.data;
    } else {
      // 处理后端返回的错误信息
      const errorMsg = response.data.msg || "获取供应商列表失败";
      console.error("获取供应商列表错误:", errorMsg);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error("获取供应商列表出错:", error);
    ElMessage.error("获取供应商列表失败，可能是因为参数错误或网络问题");
  }
};
</script>
